package com.mydemo.springlearning.functions.spi.java;

import com.mydemo.springlearning.functions.spi.java.annotation.InjectThis;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.ServiceLoader;

/**
 * @author hd
 * @date 2022-07-25 17:23
 * @description
 */
@Service
public class SPISpringService {

    @Bean
    public ActSomething getAct() {
        ServiceLoader<ActSomething> actors = ServiceLoader.load(ActSomething.class);
        ActSomething returnValue = null;
        int count = 0;
        for (ActSomething actor : actors) {
            InjectThis annotation = actor.getClass().getAnnotation(InjectThis.class);
            if (annotation != null) {
                returnValue = actor;
                count++;
                if(count>1){
                    throw new RuntimeException("使用@InjectThis注解有多个");
                }
            }
        }
        return returnValue != null ? returnValue : new ActSomethingDefaultImpl();
    }
}
